package conqueror.com.systemupdate.fragment;


import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import conqueror.com.systemupdate.R;
import conqueror.com.systemupdate.bean.NetBean;
import conqueror.com.systemupdate.config.Contans;
import conqueror.com.systemupdate.download.DownloadManager;
import conqueror.com.systemupdate.util.PreferenceUtils;

public class OnlineCheckFragment extends Fragment {


    private static final String TAG = "OnlineCheckFragment";

    private TextView mOnlineVersionCode;
    private TextView mTvShowMessage;
    private Button mBtOnlineCheck;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_online_checked, container, false);
        mOnlineVersionCode = (TextView) view.findViewById(R.id.tv_onlineVersionCode);
        mTvShowMessage = (TextView) view.findViewById(R.id.tv_showMessage);
        mBtOnlineCheck = (Button) view.findViewById(R.id.bt_onlineCheck);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        PreferenceUtils.putString(getActivity(), "Fragment", "OnlineCheckFragment");

        /*
         * 用来比较两个的版本
         * String[] split = Build.DISPLAY.split("_");
         * String s = split[3];
         * int i = Integer.parseInt(s);
         * int result = Build.DISPLAY.compareTo("BS360_H01_V01_20160816");
         */
        //获取系统的设备型号
        final String displayVersion = Build.DISPLAY;
        mOnlineVersionCode.setText(displayVersion);

        mBtOnlineCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog dialog = new ProgressDialog(getActivity(), ProgressDialog.STYLE_HORIZONTAL);
                dialog.setMessage("检查更新...");
                dialog.setCanceledOnTouchOutside(false);//点击dialog以外而不是去焦点
                dialog.show();
                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                attributes.height = 200;
                attributes.width = 300;
                dialog.getWindow().setAttributes(attributes);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //按下后联网检查，是否有更新的系统
                        RequestParams requestParams = new RequestParams(Contans.LOAD_URL);
                        x.http().get(requestParams, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String result) {
                                Log.e(TAG, "----onSuccess--------" + result);
                                Gson gson = new Gson();
                                NetBean netBean = gson.fromJson(result, NetBean.class);
                                NetBean.OtaBean ota = netBean.ota;
                                if (displayVersion.equals(ota.lastVersion)) {//如果本地的版本和服务器的lastVersion相等
                                    dialog.dismiss();
                                    updateDialog(ota.url, ota.version, ota.context);//对话框
                                } else {
                                    //不需要更新，显示mTvShowMessage
                                    mTvShowMessage.setVisibility(View.VISIBLE);
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                Log.e(TAG, "----onError--------" + ex);
                                Toast.makeText(getActivity(), "当前网络不佳，联网后重试", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onCancelled(CancelledException cex) {
                                Log.e(TAG, "----onCancelled--------" + cex);
                            }

                            @Override
                            public void onFinished() {
                                Log.e(TAG, "----onFinished--------");
                                dialog.dismiss();
                            }
                        });
                    }
                }).start();


            }
        });
    }


    /**
     * dialog，确定更新或者不更新
     */
    private void updateDialog(final String url, final String fileName, final String fileContent) {
        //挂载View并初始化
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View localView = inflater.inflate(R.layout.local_dialog, (ViewGroup) getView().findViewById(R.id.local_dialog_parent));
        Button btnEnsure = (Button) localView.findViewById(R.id.bt_localDialogOK);
        TextView tvDialogMessage = (TextView) localView.findViewById(R.id.tv_dialogMessage);
        Button btnCancel = (Button) localView.findViewById(R.id.bt_localDialogCancel);
        tvDialogMessage.setText("检测到新版本：\n" + fileName + "\n" + "是否进行更新？");

        //获取biulder
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //将自己的view设置到dialog上
        final AlertDialog dialog = builder.setView(localView).create();
        dialog.setCanceledOnTouchOutside(false);//点击dialog以外而不是去焦点
//        dialog.setCancelable(false);//按back键也是没有用的
        dialog.show();

        //自定义的确定按钮
        btnEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //开始下载：
                        try {
                            DownloadManager.getInstance().startDownload(url, fileName, "/sdcard/update.zip", fileContent, true, false, null);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
//                取代页面：
                        FragmentTransaction transaction = getFragmentManager().beginTransaction();
                        OnlineDownloadFragment fragment = new OnlineDownloadFragment();
                        transaction.replace(R.id.fl_onlineContainer, fragment);
                        transaction.commit();
                        dialog.dismiss();
                    }
                }).start();

            }
        });
        //自定义取消按钮
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }


//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        PreferenceUtils.putString(getActivity(), "Fragment", "OnlineCheckFragment");
//    }
}
